import Setting from '@/setting';
import Vue from 'vue';
const that = Vue.prototype;

/* 表头按钮 */

/**
 * 获取一般按钮
 * @param { h } 要渲染的h函数
 * @param { item } 当前渲染按钮数据
*/
const getButton = (h, item) => {
  if (!item.method) { item.method = () => {}; }
  return <el-button
    type={ item.type }
    size={ item.size }
    icon={item.icon}
    loading={item.loading}
    disabled={item.disabled}
    onClick={ () => { item.method() } }
  >{item.label}</el-button>
}
/**
 * 获取导入按钮
 * @param { h } 要渲染的h函数
 * @param { item } 当前渲染按钮数据
 * @param { data } 上传时附带的额外参数
 * @param { handleUploadSuccess } 导入成功回调方法
 * @param { handleUploadError } 导入错误回调方法
 * @param { handleBeforeUpload } 上传前回调方法
*/
const getImportButton = (h, item) => {
  if (item.showCondition === false) { return <span></span> }
  const buttonStyle = `margin: 0px 10px;`;
  const [ uploadSuccess, handleUploadError, handleBeforeUpload ] = getFinalMethods(item);
  const acceptFormats = item.accept || ['.xlsx', '.xls', '.csv'];
  let type = 'text'
  if (item.type && item.type !== 'import') type = item.type;
  return <el-upload
    data={item.data}
    style={buttonStyle}
    show-file-list={false}
    propsOnSuccess={(res) => { uploadSuccess(res) }}
    propsOnError={() => { handleUploadError() }}
    beforeUpload={file => handleBeforeUpload(file, acceptFormats)}
    accept={acceptFormats.join(', ')}
    action={`${Setting.uploadBaseURL}${item.action}`}
    disabled={item.disabled}
  >
    <el-button
      type={ type }
      size={item.size || 'mini'}
      disabled={item.disabled}
      loading={item.loading}
    >{item.label ?? '模板导入'}
    </el-button>
  </el-upload>
}
/**
 * 获取最终处理后的上传方法
 * @param { methods } 上传方法对象集
 * @param { loadingFn } 处理loading状态方法
 * @param { openLoading } 打开loading方法
 * @param { closeLoading } 关闭loading方法
*/
const getFinalMethods = (item) => {
  let { handleUploadSuccess = () => {}, handleUploadError, handleBeforeUpload } = item.methods ?? {};
  const openLoading = item.loadingFn ? () => { item.loadingFn(true); } : item.openLoading;
  const closeLoading = item.loadingFn ? () => { item.loadingFn(false); } : item.closeLoading;
  if (!handleUploadError) {
    handleUploadError = () => {
      closeLoading();
      that.$message.error('上传失败');
    }
  }
  const beforeUpload = () => {
    if (handleBeforeUpload) {
      return handleBeforeUpload();
    }
    openLoading();
  }
  const uploadSuccess = res => {
    closeLoading();
    if (res?.code == 200 || res?.code == 0) {
      that.$message.success('导入成功');
      handleUploadSuccess(res);
    } else {
      that.$message.error(res.retMessage || res.msg)
    }
  }
  return [ uploadSuccess, handleUploadError, beforeUpload ];
}

// 获取按钮栏（默认文本）集合
export const getBtnsBar = (h, list, position = 'end') => {
  return <el-row type="flex" justify={position}>{
    list && list.map(item => {
      if (item.isImport || item.type === 'import') {
        return getImportButton(h, item)
      }
      return getButton(h, item)
    })
  }</el-row>
}

// 获取格式化的按钮item
const getFormatPropsItem = (btnItem, configs = {}) => {
  const size = configs?.size ?? 'mini'
  const type = configs?.type ?? 'primary'
  const newItem = {
    ...btnItem,
    ...configs,
    size: btnItem.size ?? size,
    type: btnItem.type ?? type,
  }
  return newItem
}

// 获取列表页面按钮栏渲染集合
export const getListPageBtnsBar = (h, list, position = 'end', configs) => {
  const fillConfigList = list.map(item => getFormatPropsItem(item, configs))
  return <el-row type="flex" justify={position}>{
    fillConfigList.map(item => {
      if (item.isImport) {
        return getImportButton(h, item)
      }
      return getButton(h, item)
    })
  }</el-row>
}

/* 表列操作按钮 */

// 获取元素位置
const getPos = (list, index) => ({
  start: index == 0,
  center: index > 0 && index < list.length - 1,
  end: index == list.length - 1
})

// 根据元素位置获取对应的margin
const getMarginStyleByPos = pos => {
  let style = ''
  if (pos.start) style = 'marginRight: 10px;'
  if (pos.center) style = 'margin: 0 10px;'
  if (pos.end) style = 'marginLeft: 10px;'
  return style
}

// 渲染el-button
const renderElButton = (h, item, row) => (
  <el-button
    slot={item.slot}
    type={item.type ?? 'text'}
    disabled={item.disabled}
    size={item.size ?? 'mini'}
    loading={item.loading}
    onClick={item.confirmTitle ? () => {} : () => item.method(row)} // confirmTitle存在，证明当前为el-popconfirm，不走按钮点击事件
  >{item.label}
  </el-button>
)

// 渲染el-popconfirm 按钮气泡确认框
const renderElPopconfirm = (h, item, row, pos) => (
  <el-popconfirm
    title={item.confirmTitle}
    style={getMarginStyleByPos(pos)}
    onConfirm={() => { item.method(row) }}
  >
    { renderElButton(h, item, row) }
  </el-popconfirm>
)

// 获取action
const getActionRender = (h, row) => {
  return (item, pos) => {
    if (item.confirmTitle) return renderElPopconfirm(h, { ...item, slot: 'reference' }, row, pos)
    return renderElButton(h, item, row)
  }
}

// 获取actions
const getActionsRender = (h, renderAction) => {
  return actionList => (
    <div class="table-action">{
      actionList.map((item, index) => renderAction(item, getPos(actionList, index)))
    }</div>
  )
}

/**
 * @param { h } 要渲染的h函数
 * @param { row } 当前操作表格行的row数据
 * @param { actionList } 要渲染的按钮列表集合
 * @param { isEnableDropdown } 是否启用多个按钮下拉模式，默认不启用
*/
export const getTableAction = ({ h, row, actionList, showBtn }, isEnableDropdown = false) => {
  const renderAction = getActionRender(h, row) // 单个action操作项的渲染方法
  const renderActions = getActionsRender(h, renderAction) // 所有actions操作集合的渲染方法
  return renderActions(actionList)
}